<template>
  <div class="page">
    <Head></Head>
    <!-- <button @click="refreshPage">刷新页面</button> -->
    <div class="head">
      <a-input-search
        class="head-input"
        v-model="name"
        placeholder="请输入主题/学科/教师名称"
        enter-button="Search"
        size="large"
        @search="getCourseList"
      />

      <!-- <a-button class="head-btn" type="primary" @click="loadViewContent(0)"
        >新增</a-button
      > -->
    </div>
    <a-row>
      <a-col :span="12" v-for="(item, index) in courseList" :key="index">
        <a-card class="card" bodyStyle=" text-align: left; ">
          <div class="card-head">
            <a-popover trigger="hover">
              <template #content>
                <p>{{ item.name }}</p>
              </template>
              <div class="title">
                {{
                  item.name.length > 8
                    ? item.name.slice(0, 8) + "..."
                    : item.name
                }}
              </div>
            </a-popover>
            <div class="card-type" v-if="item.recordingStatus == 1">磨课中</div>
            <div class="card-type1" v-if="item.recordingStatus == 2">
              已结束
            </div>
            <div class="card-type2" v-if="item.recordingStatus == 0">
              未开始
            </div>
          </div>
          <div class="mt-10">
            <span>学科：{{ item.subjectName }}</span>
            <span class="ml-10">磨课老师：{{ item.teacherName }}</span>
          </div>
          <div class="mt-10">
            录制方式：{{ item.recordingMethod ? "手动录制" : "自动录制" }}
          </div>
          <div class="card-btn">
            <div class="time">
              <!-- <span> {{ item.startTime }}</span>
              <span v-if="item.endTime"> {{ `~` + item.endTime }}</span> -->
              <span>{{ formatTimeRange(item) }}</span>
            </div>
            <!-- 录制状态  0 未开始 1 录制中 2 录制成功  3录制失败 -->
            <!-- <div class="btn" @click="$refs.LocalRef.show(item)">进入课堂</div> -->
            <!-- <div class="btn" @click="$refs.NetworkRef.show(item)">进入课堂</div> -->

            <div
              class="btn"
              @click="toDetail(item)"
              v-if="item.recordingStatus == 0 || item.recordingStatus == 1"
            >
              进入课堂
            </div>
            <div
              class="btn1"
              @click.stop="save"
              v-if="item.recordingStatus == 3"
              @click="uploadVideos(item)"
            >
              上传视频
            </div>

            <!-- toDetail(item) -->

            <!-- <a-upload
              action="http://cs.xmmillions.com:18082/client/uploadVideo"
              list-type="picture"
              @change="handleAvatarSuccess"
              :before-upload="beforeUpload"
              :customRequest="uploadFlowPic"
              :data="{
                macAddress: '00:1A:2B:3C:4D:5E',
                businessId: item.id,
                businessType: 1,
                fileType: 1,
                videoLength: 5000,
              }"
              name="videoFile"
              v-model:file-list="fileList"
              accept=".mp4"
            >
            </a-upload> -->

            <!-- <div class="btn1" @click="$refs.UploadRef.show(item)">
              重新上传1
            </div> -->
          </div>
        </a-card>
      </a-col>
    </a-row>
    <a-empty class="empty" v-if="courseList.length <= 0" />
    <div class="page-num">
      <a-pagination
        class="pagination"
        v-if="total > 0"
        v-model:current="current1"
        :total="total"
        show-size-changer
        show-quick-jumper
        @change="onChange"
      />
      <div class="page-skip">
        跳转至
        <a-input
          v-model="query.pageNum"
          @change="goToList()"
          class="page-input"
        />
        页
      </div>
    </div>

    <Local ref="LocalRef"></Local>
    <Network ref="NetworkRef"></Network>
    <Upload ref="UploadRef"></Upload>
    <Set ref="setRef"></Set>
  </div>
</template>
<script>
import { ipcApiRoute } from "@/utils/ipcMainApi";
import { getCourseList } from "@/api/course.js";
import { ipc } from "@/utils/ipcRenderer";
import storage from "store2";
import { toRaw } from "vue";
import { uploadVideo } from "@/api/file.js";
import axios from "axios";

import Local from "../components/local.vue";
import Network from "../components/network.vue";

import Upload from "../components/upload.vue";
import Set from "../../../components/set.vue";

const fileList = [];

export default {
  components: {
    Local,
    Network,
    Upload,
    Set,
  },
  data() {
    return {
      file_list: fileList,
      action_url: "",
      image_info: [],
      num: 0,
      servicAddress: "",
      dir_path: "D:\\www\\ee",
      views: [
        {
          type: "vue",
          content: "#/special/broadcast",
          windowName: "磨课录制",
          windowTitle: "磨课录制",
        },
      ],
      html: [
        {
          type: "web",
          // content: "https://www.bilibili.com/",
          content: "https://www.baidu.com/",
          windowName: "window-web",
          windowTitle: "bilibili",
        },
        {
          type: "html",
          content: "/public/html/view_example.html",
        },
      ],
      courseList: [],
      current1: 1,
      pageSize: 6,
      formState: {},
      newsubwinContentsId: "",
      query: {
        macAddress: "",
        pageNum: "",
        pageSize: "",
      },
      name: "",
      total: 0,
      intervalId: null, // 用于存储定时器的ID
    };
  },
  mounted() {
    console.log(window.api);
    this.getHost();
    // 设置定时器，每分钟调用一次 getCourseList 方法
    this.intervalId = setInterval(this.getCourseList, 60000);
  },
  beforeDestroy() {
    // 在组件销毁前清除定时器
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
  created() {
    this.getCourseList();
  },
  methods: {
    uploadFlowPic(e) {
      // console.log(e, "eeeeeeeeeee");
    },
    beforeUpload(file) {
      // let isAllowed = true;
      // const type = ["mp4"];
      // if (
      //   !type.includes(
      //     file.name.split(".")[file.name.split(".").length - 1].toLowerCase()
      //   )
      // ) {
      //   isAllowed = false;
      //   this.$message.error("格式不正确");
      //   return isAllowed;
      // }
      // if (this.FormData.length >= 1) {
      //   isAllowed = false;
      //   this.$message.error("只允许上传1个！");
      //   return isAllowed;
      // }
      // return isAllowed;
    },

    handleAvatarSuccess(e) {
      this.fileList = [];

      if (e) {
      }
      // console.log(this.fileList, "fileList");
      // const formData = new FormData();
      // formData.append("macAddress", "00:1A:2B:3C:4D:5E");
      // formData.append("businessId", this.businessId);
      // formData.append("businessType", 1);
      // formData.append("fileType", 1);
      // formData.append("videoLength", 5000);
      // formData.append("videoFile", this.blob, "recorded.mp4");
      // this.uploadVideo(formData);
      // console.log(this.blob, "视频文件");
    },

    getHost() {
      ipc.invoke(ipcApiRoute.checkHttpServer, {}).then((r) => {
        if (r.enable) {
          this.servicAddress = r.server;
          storage.set("httpServiceConfig", r);

          // url转换
          const host = r.server || "http://localhost:7071";
          let uri = ipcApiRoute.uploadFile;
          let url = uri.split(".").join("/");
          this.action_url = host + "/" + url;
        }
      });
    },
    refreshPage() {
      location.reload();
    },

    goToList() {
      if (this.query.pageNum == "") {
        this.current1 = 1;
      } else {
        this.current1 = this.query.pageNum;
      }
      this.getCourseList();
    },

    //获取课程列表
    async getCourseList() {
      try {
        const res = await getCourseList({
          searchKey: this.name,
          macAddress: localStorage.getItem("macAddress"),
          pageNum: this.current1,
          pageSize: this.pageSize,
        });
        this.courseList = res.data.pageList;
        this.total = res.data.total;
        let _this = this;
        this.courseList.forEach((element) => {
          if (element.recordingMethod == 0 && element.recordingStatus == 0) {
            // element.startTime  开始    timestamp 当前时间  difference 相隔

            let timestamp = new Date();
            let date = new Date(element.startTime);
            let difference = 0;
            difference = date - timestamp;
            if (difference < 3000) {
              _this.startRecord(element);
            }
          }
        });
      } catch (error) {}
    },

    // 开始播放
    async startRecord(row) {
      this.formState = this.getStat();
      let rtspUrl = this.formState.network + this.formState.port;
      try {
        const response = await axios.get(
          `http://192.168.1.117:8080/stream/startRecord?rtspUrl=${rtspUrl}&fileName=${row.id}`
        ); // 替换为你的API URL
      } catch (error) {
        console.error("There was an error!", error);
      }
    },

    // 获取状态
    getStat() {
      if (localStorage.getItem("set")) {
        return JSON.parse(localStorage.getItem("set"));
      } else {
        return {
          source: "",
        };
      }
    },

    toDetail(item) {
      let info = "";
      info = this.getStat();
      if (info.source == "") {
        this.$message.error("请设置相关配置");
        this.$refs.setRef.show(item);

        return;
      }
      if (info.source == "网络摄像头") {
        this.$refs.NetworkRef.show(1, item);
      } else {
        this.$refs.LocalRef.show(1, item);
      }

      // if (info.source == "网络摄像头") {
      //   this.views[0].content =
      //     "#/special/network" + "?id=" + item.id + "&type=1";
      //   ipc.invoke(ipcApiRoute.createWindow, toRaw(this.views[0])).then((r) => {
      //     console.log(r);
      //   });
      // } else {
      //   this.views[0].content =
      //     "#/special/broadcast" + "?id=" + item.id + "&type=1";
      //   ipc.invoke(ipcApiRoute.createWindow, toRaw(this.views[0])).then((r) => {
      //     console.log(r);
      //   });
      // }
    },
    getMacAddress() {},
    onChange() {
      this.getCourseList({
        pageNum: this.current1,
        pageSize: this.pageSize,
        searchKey: "",
        macAddress: localStorage.getItem("macAddress"),
      });
    },
    loadViewContent(index) {
      ipc
        .invoke(ipcApiRoute.createWindow, toRaw(this.html[index]))
        .then((r) => {
          console.log(r);
        });
    },
    removeViewContent(index) {
      ipc
        .invoke(ipcApiRoute.removeViewContent, toRaw(this.html[index]))
        .then((r) => {
          console.log(r);
        });
    },
    createWindow(index) {
      ipc
        .invoke(ipcApiRoute.createWindow, toRaw(this.views[index]))
        .then((id) => {
          this.newsubwinContentsId = id;
        });
      // ipc.send("frommainwin", "主动发送我是渲染进程的test2");
      // ipc.on("sendtosubwin", (event, value) => {
      //   console.log("接收主程序通讯：", value); // prints "我是主进程的test1"
      //   this.$message.info("接收主程序通讯：" + value);
      //   event.sender.send("frommainwin", "收到主程序-回复主程序消息");
      // });
    },
    openDirectry(id) {
      ipc.invoke(ipcApiRoute.openDirectory, { id: id }).then((res) => {
        //console.log('res:', res)
      });
    },
    selectDir() {
      ipc.invoke(ipcApiRoute.selectFolder, "").then((r) => {
        this.dir_path = r;
        this.$message.info(r);
      });
    },
    messageShow() {
      ipc.invoke(ipcApiRoute.messageShow, "").then((r) => {
        this.$message.info(r);
      });
    },
    messageShowConfirm() {
      ipc.invoke(ipcApiRoute.messageShowConfirm, "").then((r) => {
        this.$message.info(r);
      });
    },

    // 上传视频
    uploadVideos(row) {
      let info = "";
      info = this.getStat();

      if (info.source == "网络摄像头") {
        try {
          const response = axios.get(
            `http://192.168.1.117:8080/stream/uploadMp4?businessId=${row.id}`
          ); // 替换为你的API URL
        } catch (error) {
          console.error("There was an error!", error);
        }
      } else {
        this.$refs.UploadRef.show(row);
      }
    },
    handleFileChange(info) {
      console.log("handleFileChange-----");
      if (this.action_url == "") {
        this.$message.error("http服务未开启");
        return;
      }
      const status = info.file.status;
      if (status !== "uploading") {
        console.log(info.file);
      }
      if (status === "done") {
        const uploadRes = info.file.response;
        console.log("uploadRes:", uploadRes);
        if (uploadRes.code !== "success") {
          this.$message.error(`file upload failed ${uploadRes.code} .`);
          return false;
        }
        this.num++;
        const picInfo = uploadRes.data;
        picInfo.id = this.num;
        picInfo.imageUrlText = "image url";
        this.image_info.push(picInfo);
        this.$message.success(`${info.file.name} file uploaded successfully.`);
      } else if (status === "error") {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
    formatTimeRange(item) {
      if (item.recordingStatus == 1) {
        // 判断是否录制中
        if (item.recordingMethod == 0) {
          // 判断是否为自动录制
          return `${item.startTime}~${item.endTime}`;
        } else {
          return `${item.startTime}`;
        }
      } else {
        return `${item.startTime}~${item.endTime}`;
      }
    },
  },
};
</script>
<style lang="less" scoped>
#app-base-file {
  padding: 0px 10px;
  text-align: left;
  width: 100%;
  .one-block-1 {
    font-size: 16px;
    padding-top: 10px;
  }

  .one-block-2 {
    padding-top: 10px;
  }

  .footer {
    padding-top: 10px;
  }
}
.page-num {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.page-input {
  width: 50px;
  margin: 0 5px;
}
.page-skip {
  display: flex;
  justify-content: center;
  align-items: center;
}
.page {
  padding: 20px 0px 20px 20px;
}

.card {
  height: 137px;
  background: #ffffff;
  border-radius: 8px 8px 8px 8px;
  border: none;
  margin-bottom: 20px;
  margin-right: 20px;

  .title {
    width: 85%;
    font-weight: 600;
    font-size: 16px;
    color: #333333;
    white-space: nowrap;
    /* 禁止文本换行 */
    overflow: hidden;
    /* 隐藏超出容器的文本 */
    text-overflow: ellipsis;
    /* 使用省略号表示溢出的文本 */
  }

  .card-type {
    min-width: 30px;
    font-size: 12px;
    background: #e3ffd8;
    color: #57eb1c;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 4px;
    border-radius: 4px;
  }

  .card-type1 {
    min-width: 30px;
    font-size: 12px;
    background: #ffeaea;
    color: #ff2d46;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 4px;
    border-radius: 4px;
  }

  .card-type2 {
    min-width: 30px;
    font-size: 12px;
    background: #f9f9f9;
    color: #7f7f7f;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 4px;
    border-radius: 4px;
  }

  .time {
    color: #a1a1a3;
    font-size: 14px;
  }

  .card-head {
    display: flex;
    justify-content: space-between;
  }

  .arco-card-body {
    text-align: left !important;
  }

  .card-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
  }

  .btn {
    // min-width: 58px;
    cursor: pointer;
    // border: 1px solid #237bff;
    // padding: 4px;
    color: #237bff;
    // border-radius: 4px;
  }

  .btn1 {
    // min-width: 58px;
    cursor: pointer;

    // border: 1px solid #d7d7d7;
    // padding: 4px;
    color: #6e6c6c;
    // border-radius: 4px;
  }
}

.head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  margin-right: 20px;

  .head-input {
    width: 219px;
    height: 37px;
    background: #fbfbfb;
    border-radius: 28px 28px 28px 28px;
    border: 1px solid #eeeeee;
  }

  .head-btn {
    width: 59px;
    height: 28px;
    background: #237dff;
    border-radius: 30px 30px 30px 30px;
  }
}

.mt-10 {
  margin-top: 10px;
}

.ml-10 {
  margin-left: 10px;
}

.empty {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 25%;
}

.pagination {
  // position: fixed;
  // right: 20px;
  // top: 80%;
  float: right;
}

.arco-upload-wrapper {
  width: 106px;
  height: 32px;
  overflow: hidden;
}

.arco-modal-body {
  padding: 0px !important;
}
</style>
